package config

import (
	"encoding/json"
	"fmt"
	"os"
	"shop/entity"
	"shop/utils/convertutil"
	"shop/utils/httputil"

	"gopkg.in/yaml.v2"
)

type sysConfig struct {
	// Mysql配置
	MysqlAddress  string `yaml:"mysqlAddress"`
	MysqlDBName   string `yaml:"mysqlDBName"`
	MysqlUsername string `yaml:"mysqlUsername"`
	MysqlPassword string `yaml:"mysqlPassword"`

	// Redis配置
	RedisAddress  string `yaml:"redisAddress"`
	RedisPassword string `yaml:"redisPassword"`

	// 腾讯云；api秘钥
	TencentCloudAppId     string `yaml:"tencentCloudAppId"`
	TencentCloudSecretId  string `yaml:"tencentCloudSecretId"` // 请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
	TencentCloudSecretKey string `yaml:"tencentCloudSecretKey"`
	// 腾讯云存储cos配置
	TencentCloudCosDomain string `yaml:"tencentCloudCosDomain"` // 腾讯云cos桶域名
	// 腾讯云短信sms配置, see: https://console.cloud.tencent.com/smsv2
	TencentCloudSmsAppId      string `yaml:"tencentCloudSmsAppId"`
	TencentCloudSmsAppKey     string `yaml:"tencentCloudSmsAppKey"`
	TencentCloudSmsTemplateId string `yaml:"tencentCloudSmsTemplateId"` // 玩家注册验证码短信模板, eg:模板-1087068的内容: 您的注册验证码：{1}，{2}秒内有效，请勿泄露。
	TencentCloudSmsSignName   string `yaml:"tencentCloudSmsSignName"`   // 申请的签名

	// 腾讯Auth2.0应用
	TencentAuth20AppId  string `yaml:"tencentAuth20AppId"`
	TencentAuth20AppKey string `yaml:"tencentAuth20AppKey"`

	// 芯烨云密钥，订单条打印机服务
	XinyeyunUsername string `yaml:"xinyeyunUsername"`
	XinyeyunApiKey   string `yaml:"xinyeyunApiKey"`
}

type MerchantConfig struct {
	ShopId            int
	MerchantName      string
	WxPayMchId        string // 微信支付商家号
	WxPayApiKey       string // 微信支付apiKey
	WxMpAppId         string // 微信小程序的appId
	WxMpAppSecret     string // 微信小程序的appSecret
	CertPEMPublicKey  string // 微信支付的tls-p12证书-PEM格式的公钥,微信退款等需要
	CertPEMPrivateKey string // 私钥
	PrinterTicket     string // 小票打印-小票打印机
	PrinterLabel      string // 小票打印-标签打印机
}

// loadSysConfig 从gitee上获取配置文件信息，gitee上的代码片段里查看文件名-打开文件后url后缀就是gistId
func loadSysConfig() *sysConfig {
	var accessToken = os.Getenv("giteeToken") // see: https://gitee.com/profile/personal_access_tokens
	if accessToken == "" {
		panic("giteeToken为空，无法从gitee上拉取配置")
	}

	url := fmt.Sprintf(`https://gitee.com/api/v5/gists/mh52ypxnuirfo98alzqgv51?access_token=%s`, accessToken) // see: https://gitee.com/api/v5/swagger#/getV5GistsId
	resp := new(struct {
		Files map[string]struct {
			Content string
		}
	})
	_ = json.Unmarshal([]byte(httputil.Get(url)), resp)
	conf := new(sysConfig)
	_ = yaml.Unmarshal([]byte(resp.Files["shop-config.yaml"].Content), conf)
	if conf.MysqlUsername == "" || conf.MysqlPassword == "" || conf.MysqlDBName == "" {
		panic("配置文件加载为空，请检查网络和gitee上是否存在配置文件")
	}
	return conf
}

func loadShopConfigs() []MerchantConfig {
	var accessToken = os.Getenv("giteeToken")
	if accessToken == "" {
		panic("giteeToken为空，无法从gitee上拉取配置")
	}

	url := fmt.Sprintf(`https://gitee.com/api/v5/gists/mh52ypxnuirfo98alzqgv51?access_token=%s`, accessToken)
	resp := new(struct {
		Files map[string]struct {
			Content string
		}
	})
	convertutil.ParseJson(httputil.Get(url), resp)
	confs := make([]MerchantConfig, 0)
	convertutil.ParseJson(resp.Files["merchant-configs.json"].Content, &confs)
	return confs
}

func loadSysRoleList() []entity.SysRole {
	var accessToken = os.Getenv("giteeToken")
	if accessToken == "" {
		panic("giteeToken为空，无法从gitee上拉取配置")
	}

	url := fmt.Sprintf(`https://gitee.com/api/v5/gists/mh52ypxnuirfo98alzqgv51?access_token=%s`, accessToken)
	resp := new(struct {
		Files map[string]struct {
			Content string
		}
	})
	_ = json.Unmarshal([]byte(httputil.Get(url)), resp)
	roles := make([]entity.SysRole, 0)
	convertutil.ParseJson(resp.Files["SysRoles.json"].Content, &roles)
	return roles
}

func GetMerchantConfByShopId(shopId int) *MerchantConfig {
	for i := range MerchantConfs {
		if MerchantConfs[i].ShopId == shopId {
			return &MerchantConfs[i]
		}
	}
	return &MerchantConfig{}
}

func GetSysRoleById(roleId int) *entity.SysRole {
	for i := range SysRoles {
		if SysRoles[i].Id == roleId {
			return &SysRoles[i]
		}
	}
	return &entity.SysRole{}
}
